<template>
  <div id="mainBox" class="flex-column h-100 relative">
    <div v-show="!fullScreen" class="flex-column h-100 statistic-box">
      <div class="flex flex-1 h-1">
        <div class="flex-column width-change pointer-auto">
          <template v-if="!onlyStationStatistics">
            <!-- 光缆统计 -->
            <div class="grid-item">
              <div class="grid-title">
                <span>
                  <i class="iconfont icon-AFShome-cable" />
                  {{ $t('OPTICAL_CABLE_STATISTICS') }}
                </span>
                <i
                  class="el-icon-full-screen"
                  @click="previewStatisics('CableStatistics', $t('OPTICAL_CABLE_STATISTICS'))"
                />
              </div>
              <div class="grid-content">
                <CableStatistics ref="statistics1" :statistics-data="statisticsData" />
              </div>
            </div>
          </template>
          <template v-else>
            <!-- 站点设备统计 -->
            <div class="grid-item">
              <div class="grid-title">
                <span>
                  <i class="iconfont icon-AFShome-cable" />
                  {{ $t('SITE_EQUIPMENT_STATISTICS') }}
                </span>
                <i
                  class="el-icon-full-screen"
                  @click="
                    previewStatisics('StationDeviceStatistics', $t('SITE_EQUIPMENT_STATISTICS'))
                  "
                />
              </div>
              <div class="grid-content">
                <StationDeviceStatistics ref="statistics1" :statistics-data="statisticsData" />
              </div>
            </div>
          </template>
          <!-- 光纤资源统计 -->
          <div class="grid-item">
            <div class="grid-title">
              <span>
                <i class="iconfont icon-AFShome-fiber" />
                {{ $t('FIBER_RESOURCE_STATISTICS') }}
              </span>
              <i
                class="el-icon-full-screen"
                @click="previewStatisics('FiberStatistics', $t('FIBER_RESOURCE_STATISTICS'))"
              />
            </div>
            <div class="grid-content">
              <FiberStatistics ref="statistics2" :statistics-data="statisticsData" />
            </div>
          </div>
        </div>
        <!-- 中间地图 -->
        <div class="flex-1 relative">
          <div v-if="previewStatisicsName !== ''" class="flex-column preview-box pointer-auto">
            <div class="flex justify-between pb-10 text-color">
              <span>{{ previewStatisicsTitle }}</span>
              <i class="el-icon-close pointer" @click="previewStatisics('', '')" />
            </div>
            <component
              :is="previewStatisicsName"
              ref="statisicsScreen"
              :is-preview="true"
              :statistics-data="statisticsData"
              :show-type="showType"
              :statics-item="staticsItem"
              @growthChange="getBizStatistics(true, 'statisicsScreen')"
            />
          </div>
        </div>
        <div class="flex-column width-change pointer-auto">
          <!-- 智能设备状态统计 -->
          <div class="grid-item">
            <div class="grid-title">
              <span>
                <i class="iconfont icon-AFShome-status" />
                {{ $t('SMART_DEVICE_STATUS_STATISTICS') }}
              </span>
              <i
                class="el-icon-full-screen"
                @click="
                  previewStatisics('OnlineStatistics', $t('SMART_DEVICE_STATUS_STATISTICS'))
                "
              />
            </div>
            <div class="grid-content">
              <OnlineStatistics
                ref="statistics3"
                :statics-item="staticsItem"
                :statistics-data="statisticsData"
              />
            </div>
          </div>
          <!-- 智能设备运行统计 -->
          <div class="grid-item">
            <div class="grid-title">
              <span>
                <i class="iconfont icon-AFShome-device" />
                {{ $t('INTELLIGENT_DEVICE_OPERATION_STATISTICS') }}
              </span>
              <i
                class="el-icon-full-screen"
                @click="
                  previewStatisics('RunStatistics', $t('INTELLIGENT_DEVICE_OPERATION_STATISTICS'))
                "
              />
            </div>
            <div class="grid-content">
              <RunStatistics ref="statistics4" :statistics-data="statisticsData" />
            </div>
          </div>
        </div>
      </div>
      <div class="flex justify-between height-change pointer-auto">
        <template v-if="!onlyStationStatistics">
          <!-- 站点统计 -->
          <div class="grid-item">
            <div class="grid-title">
              <span>
                <i class="iconfont icon-AFShome-station" />
                {{ showType === 'station' ? $t('SITE_STATISTICS') : $t('SMART_STATISTICS') }}
              </span>
              <i
                class="el-icon-full-screen"
                @click="
                  previewStatisics(
                    'StationStatistics',
                    showType === 'station' ? $t('SITE_STATISTICS') : $t('SMART_STATISTICS')
                  )
                "
              />
            </div>
            <div class="grid-content">
              <StationStatistics
                ref="statistics5"
                :show-type="showType"
                :statistics-data="statisticsData"
              />
            </div>
          </div>
        </template>
        <template v-else>
          <!-- ODF架端口状态统计 -->
          <div class="grid-item">
            <div class="grid-title">
              <span>
                <i class="iconfont icon-AFShome-station" />
                {{
                  statisticsData.lightPortStatusList.length > 1
                    ? $t('AFS_PORT_STATUS_STATISTICS')
                    : $t('ODF_PORT_STATUS_STATISTICS')
                }}
              </span>
              <i
                class="el-icon-full-screen"
                @click="
                  previewStatisics(
                    'DevicePortsStatistics',
                    statisticsData.lightPortStatusList.length > 1
                      ? $t('AFS_PORT_STATUS_STATISTICS')
                      : $t('ODF_PORT_STATUS_STATISTICS')
                  )
                "
              />
            </div>
            <div class="grid-content">
              <DevicePortsStatistics ref="statistics5" :statistics-data="statisticsData" />
            </div>
          </div>
        </template>
        <!-- 业务统计 -->
        <div class="grid-item">
          <div class="grid-title">
            <span>
              <i class="iconfont icon-AFShome-biz" />
              {{ $t('BIZ_STATISTICS') }}
            </span>
            <i
              class="el-icon-full-screen"
              @click="previewStatisics('BizStatistics', $t('BIZ_STATISTICS'))"
            />
          </div>
          <div class="grid-content">
            <BizStatistics
              ref="statistics6"
              :statistics-data="statisticsData"
              :statics-item="staticsItem"
            />
          </div>
        </div>
        <!-- 业务环比增长趋势 -->
        <div class="grid-item">
          <div class="grid-title">
            <span>
              <i class="iconfont icon-AFShome-trend" />
              {{ $t('BUSINESS_GROWTH_TREND') }}
            </span>
            <i
              class="el-icon-full-screen"
              @click="previewStatisics('GrowthStatistics', $t('BUSINESS_GROWTH_TREND'))"
            />
          </div>
          <div class="grid-content">
            <GrowthStatistics
              ref="statistics7"
              :statistics-data="statisticsData"
              @growthChange="getBizStatistics(true, 'statistics7')"
            />
          </div>
        </div>
        <!-- 告警统计 -->
        <div class="grid-item">
          <div class="grid-title">
            <span>
              <i class="iconfont icon-AFShome-alarm" />
              {{ $t('ALARM_STATISTICS') }}
            </span>
            <i
              class="el-icon-full-screen"
              @click="previewStatisics('AlarmStatistics', $t('ALARM_STATISTICS'))"
            />
          </div>
          <div class="grid-content">
            <AlarmStatistics ref="statistics8" :statistics-data="statisticsData" />
          </div>
        </div>
        <!-- 智能设备端口统计 -->
        <div class="grid-item">
          <div class="grid-title">
            <span>
              <i class="iconfont icon-AFShome-port" />
              {{ $t('SMART_DEVICE_PORT_STATISTICS') }}
            </span>
            <i
              class="el-icon-full-screen"
              @click="previewStatisics('PortsStatistics', $t('SMART_DEVICE_PORT_STATISTICS'))"
            />
          </div>
          <div class="grid-content">
            <PortsStatistics
              ref="statistics9"
              :statistics-data="statisticsData"
              :statics-item="staticsItem"
            />
          </div>
        </div>
      </div>
      <MarqueeBox v-if="!fullScreen" @locateAlarm="locateAlarm" />
    </div>
    <div class="map-box">
      <MapView
        ref="mapContent"
        :statics-item="staticsItem"
        :full-screen="fullScreen"
        :region-data="regionData"
        :preview-statisics-name="previewStatisicsName"
        @regionChanged="regionChanged"
        @operateFullScreen="operateFullScreen"
      />
    </div>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import homeApi from '@/api/oen/HomeApi'
  import CableStatistics from './components/charts/CableStatistics'
  import StationDeviceStatistics from './components/charts/StationDeviceStatistics'
  import FiberStatistics from './components/charts/FiberStatistics'
  import OnlineStatistics from './components/charts/OnlineStatistics'
  import RunStatistics from './components/charts/RunStatistics'
  import StationStatistics from './components/charts/StationStatistics'
  import DevicePortsStatistics from './components/charts/DevicePortsStatistics'
  import BizStatistics from './components/charts/BizStatistics'
  import GrowthStatistics from './components/charts/GrowthStatistics'
  import AlarmStatistics from './components/charts/AlarmStatistics'
  import PortsStatistics from './components/charts/PortsStatistics'
  import MapView from './components/map'
  import MarqueeBox from './components/MarqueeBox.vue'

  export default {
    name: 'Home',
    components: {
      CableStatistics,
      StationDeviceStatistics,
      FiberStatistics,
      OnlineStatistics,
      RunStatistics,
      StationStatistics,
      DevicePortsStatistics,
      BizStatistics,
      GrowthStatistics,
      AlarmStatistics,
      PortsStatistics,
      MapView,
      MarqueeBox
    },
    data() {
      return {
        statisticsData: {
          cableList: [],
          fiberList: [],
          stationList: [],
          bizStatList: [],
          alarmStatus: [],
          smartDeviceList: [],
          chainRatioList: [],
          odfPortStatusList: [],
          lightPortStatusList: [],
          deviceTypeList: [],
          onlineStatus: {},
          runStatus: {},
          portStatus: {}
        },
        regionData: {
          showRegionIds: [],
          regionIds: []
        },
        filterType: 'REGIONS',
        onlyStationStatistics: false,
        showType: 'station',
        staticsItem: {
          width: 0,
          height: 200
        },
        previewStatisicsName: '',
        previewStatisicsTitle: ''
      }
    },
    computed: {
      ...mapGetters([
        'getTheme',
        'notifyList',
        'dictMap',
        'baseRegionList',
        'regionStationTree',
        'fullScreen',
        'mapType',
        'ticktack',
        'filterStationIds'
      ])
    },
    watch: {
      getTheme(val) {
        // 监听主题切换
        this.renderCharts()
      },
      'marqueeList.length'() {
        this.getAlarmStat()
      },
      ticktack() {
        !this.fullScreen && this.getData()
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.mapType === 'GisView') {
        const mapBox = this.$refs.mapContent.$refs.mapContainer
        const zoom = mapBox.map.getView().getZoom() // 获取当前地图的缩放级别
        const center = mapBox.map.getView().getCenter()
        this.$store.commit('setCurZoomView', { zoom, center })
      }
      next()
    },
    mounted() {
      this.$nextTick(() => {
        this.setGridItem()
      })
      window.addEventListener('resize', this.setGridItem)
    },
    activated() {
      // this.getData()
      this.$refs.mapContent.refreshTopo()
      this.filterStationIds.length &&
        this.$store.commit('setStationSelected', this.filterStationIds)
      this.$nextTick(() => {
        this.setGridItem()
      })
      window.addEventListener('resize', this.setGridItem)
    },
    deactivated() {
      window.removeEventListener('resize', this.setGridItem)
    },
    methods: {
      // 中间大屏预览统计图
      previewStatisics(name, title) {
        this.previewStatisicsName = name
        this.previewStatisicsTitle = title
        this.$nextTick(() => {
          this.$refs['statisicsScreen'] && this.$refs['statisicsScreen'].renderChart()
        })
      },
      // 筛选的站点信息改变
      regionChanged(data, isView) {
        this.filterType = data.filterType
        const checkedNodeIds = data.checkedNodes.map(i => i.regionId)
        const regionIds = this.baseRegionList
          .filter(i => i.parentIds && i.parentIds.some(j => checkedNodeIds.includes(j)))
          .map(i => i.regionId)
        let children = []
        if (!data.stationSelected && data.checkedNodes.length === 1) {
          const regionId = data.checkedNodes[0].regionId
          children = this.baseRegionList
            .filter(i => i.parentId === regionId && i.regionType === 'REGION' && i.hasChild)
            .map(i => i.regionId)
        }
        const regionIds1 = Array.from(new Set([...checkedNodeIds, ...regionIds, ...children]))
        this.regionData = {
          ...data,
          showRegionIds: children.length ? children : data.showRegionIds,
          regionIds: regionIds1
        }
        this.onlyStationStatistics = false

        if (data.stationSelected && data.checkedNodes.length === 1) {
          this.onlyStationStatistics = true
          !isView && this.locateAlarm(data.checkedNodes[0])
        }
        const activeNodes = data.stationSelected ? data.checkedNodes.map(i => i.regionId) : []
        this.$store.commit('setGisActived', {
          cableIds: [],
          nodeIds: activeNodes,
          color: '',
          filterType: data.filterType
        })

        this.showType = data.stationSelected && data.checkedStation.length > 1 ? 'smart' : 'station'
        if (data.filterType === 'CABLE') {
          this.regionData.showRegionIds = this.baseRegionList
            .filter(i => i.regionType === 'STATION' && regionIds1.includes(i.regionId))
            .map(i => i.regionId)
          this.showType = 'smart'
        }
        this.$store.commit('setStationSelected', this.regionData.regionIds)
        this.$store.commit('setFilterStationIds', this.regionData.regionIds)
        this.$nextTick(() => {
          // console.log('regionIds1', regionIds1)
          regionIds1.length && this.getData()
          regionIds1.length &&
            this.$refs.mapContent.$refs.mapContainer.fitView(this.regionData.regionIds)
        })
      },
      // 获取统计数据
      getData() {
        // console.log('getData-----------', this.regionData.showRegionIds)
        if (!this.regionData.showRegionIds.length) return
        this.getLeftStatistics()
        this.getBizStatistics()
        this.getDeviceOnline()
        this.getAlarmStat()
        this.getDeviceRun()
        this.getPortStatus()
      },
      getLeftStatistics() {
        homeApi
          .mergeHistogram({
            showRegionIds: this.regionData.showRegionIds,
            regionIds: this.regionData.regionIds
          })
          .then(res => {
            this.statisticsData = {
              ...this.statisticsData,
              ...res
            }
            this.$nextTick(() => {
              this.$refs['statistics1'] && this.$refs['statistics1'].renderChart()
              this.$refs['statistics2'] && this.$refs['statistics2'].renderChart()
              this.$refs['statistics5'] && this.$refs['statistics5'].renderChart()
            })
          })
          .catch(() => {})
      },
      getBizStatistics(growthOnly, componentName = 'statistics7') {
        const growthData = this.$refs[componentName]
          ? this.$refs[componentName].growthData
          : { statType: 'MONTH', range: 36 }
        const otherName = componentName === 'statistics7' ? 'statisicsScreen' : 'statistics7'
        this.$refs[otherName] && (this.$refs[otherName].dateValue = growthData.statType)
        homeApi
          .mergeBizStat({
            ...growthData,
            showRegionIds: this.regionData.showRegionIds,
            regionIds: this.regionData.regionIds
          })
          .then(res => {
            this.statisticsData.bizStatList = res.bizStatList
            this.statisticsData.chainRatioList = res.chainRatioList
            this.$nextTick(() => {
              this.$refs['statistics6'] && !growthOnly && this.$refs['statistics6'].renderChart()
              this.$refs['statistics7'] && this.$refs['statistics7'].renderChart(true)
              this.$refs['statisicsScreen'] && this.$refs['statisicsScreen'].renderChart(true)
            })
          })
          .catch(() => {})
      },
      getDeviceOnline() {
        homeApi
          .deviceOnlineStatus(this.regionData.regionIds)
          .then(res => {
            this.statisticsData.onlineStatus = res
            this.$nextTick(() => {
              this.$refs['statistics3'] && this.$refs['statistics3'].renderChart()
            })
          })
          .catch(() => {})
      },
      getAlarmStat() {
        homeApi
          .alarmStat({
            regionIds: this.regionData.regionIds
          })
          .then(res => {
            this.statisticsData.alarmStatus = res
            this.$nextTick(() => {
              this.$refs['statistics8'] && this.$refs['statistics8'].renderChart()
            })
          })
          .catch(() => {})
      },
      getDeviceRun() {
        homeApi
          .deviceRunStatus(this.regionData.regionIds)
          .then(res => {
            this.statisticsData.runStatus = res
            this.$nextTick(() => {
              this.$refs['statistics4'] && this.$refs['statistics4'].renderChart()
            })
          })
          .catch(() => {})
      },
      getPortStatus() {
        homeApi
          .portStatus(this.regionData.regionIds)
          .then(res => {
            this.statisticsData.portStatus = res
            this.$nextTick(() => {
              this.$refs['statistics9'] && this.$refs['statistics9'].renderChart()
            })
          })
          .catch(() => {})
      },
      setGridItem() {
        const mainBox = document.querySelector('#mainBox')
        if (!mainBox || this.fullScreen) return
        const totalWidth = mainBox.clientWidth
        const totalHeight = mainBox.clientHeight
        const width = parseInt((totalWidth - 20) / 5)
        const height = parseInt((totalHeight - 15 - 30) / 3)
        this.staticsItem = {
          width: width,
          height: height
        }
        const gridItems = document.querySelectorAll('.grid-item')
        gridItems.forEach(i => {
          i.style.width = width + 'px'
          i.style.height = height + 'px'
        })
        this.renderCharts()
      },
      renderCharts() {
        this.$nextTick(() => {
          for (let i = 1; i < 10; i++) {
            this.$refs['statistics' + i] && this.$refs['statistics' + i].renderChart()
          }
          this.$refs['statisicsScreen'] && this.$refs['statisicsScreen'].renderChart()
        })
      },
      operateFullScreen(fullScreen) {
        this.$refs.mapContent.$refs.businessGis &&
          (this.$refs.mapContent.$refs.businessGis.animation = fullScreen)
        if (fullScreen) {
          this.hideStatistics()
        } else {
          this.showStatistics()
        }
      },
      hideStatistics() {
        const heighthange = document.querySelectorAll('.height-change')
        const widthChange = document.querySelectorAll('.width-change')
        heighthange.forEach(i => {
          i.classList.add('overflow-hidden')
          i.style.maxHeight = 0
        })
        widthChange.forEach(i => {
          i.style.maxWidth = 0
        })
        this.$store.commit('setFullScreen', true)
      },
      showStatistics() {
        this.$store.commit('setFullScreen', false)
        const _this = this
        setTimeout(() => {
          const heighthange = document.querySelectorAll('.height-change')
          const widthChange = document.querySelectorAll('.width-change')
          heighthange.forEach(i => {
            i.classList.remove('overflow-hidden')
            i.style.maxHeight = '33%'
          })
          widthChange.forEach(i => {
            i.style.maxWidth = '20%'
          })
          _this.renderCharts()
        })
      },
      locateAlarm(data) {
        const regionIds = this.regionData.regionIds
        this.$refs.mapContent.locateAlarm(data, regionIds.includes(data.regionId))
      }
    }
  }
</script>

<style lang="scss">
  @import '@/assets/css/mixin.module.scss';

  .map-box {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
  }

  .statistic-box {
    padding-top: 5px;
    pointer-events: none;
    z-index: 2;
  }

  .pointer-auto {
    pointer-events: auto;
  }

  .grid-item {
    display: flex;
    flex-direction: column;

    .grid-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 15px;
      font-size: 15px;
      line-height: 35px;
      // white-space: nowrap;
      white-space: pre;
      background-size: 100% 100%;

      @include themeify {
        color: themed('homeGridTitle');
        background-image: url(themed('homeGridTitleBg'));
      }

      .iconfont {
        margin-right: 5px;
        font-size: 15px;
      }
      .el-icon-full-screen {
        cursor: pointer;
      }
    }

    .grid-content {
      padding: 5px;
      flex: 1;
      box-sizing: border-box;

      @include themeify {
        background-color: themed('homeGridbg');
        border: 1px solid themed('homeGridborder');
      }
    }
  }

  .width-change .grid-item {
    margin-bottom: 5px;
  }

  .width-change {
    max-width: 20%;
    transition: all 0.5s;
    overflow: hidden;
  }

  .height-change {
    max-height: 33%;
    transition: all 0.5s;
  }

  .chart-statistics-select {
    position: absolute !important;
    z-index: 2;

    input {
      padding: 0 20px 0 5px;

      @include themeify {
        border: 1px solid themed('homeSelectBorder') !important;
        background: themed('homeSelectBg') !important;
        color: themed('homeSelectColor') !important;
      }
    }

    .el-input__suffix {
      right: 0;

      .el-input__icon {
        @include themeify {
          color: themed('homeSelectColor') !important;
        }
      }
    }
  }
  .preview-box {
    width: calc(100% - 20px);
    height: calc(100% - 10px) !important;
    margin: 0 auto;
    padding: 10px;
    box-sizing: border-box;

    @include themeify {
      background-color: themed('homeGridbg');
      border: 1px solid themed('homeGridborder');
    }
  }
</style>
